package com.qingyun.web.controller.pcapi.order;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyV3Result;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.qingyun.common.annotation.Log;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.model.TiktokProxyVo;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.enums.BusinessType;
import com.qingyun.common.utils.QrcodeGeneratorUtils;
import com.qingyun.common.utils.StringUtils;
import com.qingyun.common.utils.ip.IpUtils;
import com.qingyun.common.utils.poi.ExcelUtil;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokGoods;
import com.qingyun.shop.domain.TiktokOrder;
import com.qingyun.shop.domain.TiktokProxyBranchConfig;
import com.qingyun.shop.domain.bo.order.TiktokOrderCreateBo;
import com.qingyun.shop.domain.bo.order.TiktokOrderQueryBo;
import com.qingyun.shop.domain.vo.OrderVo;
import com.qingyun.shop.domain.vo.TiktokGoodsVo;
import com.qingyun.shop.domain.vo.TiktokOrderDetailVo;
import com.qingyun.shop.domain.vo.TiktokOrderListVo;
import com.qingyun.shop.service.ITiktokGoodsService;

import com.qingyun.shop.service.ITiktokOrderService;
import com.qingyun.shop.service.ITiktokProxyBranchConfigService;
import com.qingyun.shop.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 订单Controller
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Validated
@Api(value = "订单控制器", tags = {"^订单管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/order")
public class TiktokOrderController extends BaseController {

    private final ITiktokOrderService iTiktokOrderService;

	private final ITiktokGoodsService iTiktokGoodsService;

	private QingYunConfig qingYunConfig;

	private WxPayService wxPayService;

	private PayService payService;

	private RedisCache redisCache;

    /**
     * 查询订单列表
     */
    @ApiOperation("^查询订单列表 order:order:list")
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo<TiktokOrderListVo> list(@Validated TiktokOrderQueryBo bo) {
        return iTiktokOrderService.queryPageList(bo);
    }

    /**
     * 导出订单列表
     */
    @ApiOperation("导出订单列表")
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @GetMapping("/export")
    public void export(@Validated TiktokOrderQueryBo bo, HttpServletResponse response) {
        List<TiktokOrderListVo> list = iTiktokOrderService.queryList(bo);
        ExcelUtil.exportExcel(list, "订单表", TiktokOrderListVo.class, response);
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("^订单id获取订单详细信息 order:order:query")
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping("/{id}")
    public AjaxResult<TiktokOrderDetailVo> getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iTiktokOrderService.queryById(id));
    }

	/**
	 * 获取订单详细信息
	 */
	@ApiOperation("^根据订单编号获取订单详细信息 order:order:query")
	@PreAuthorize("@ss.hasPermi('order:order:query')")
	@GetMapping("/detail/{orderNum}")
	public AjaxResult<TiktokOrderDetailVo> getInfo(@PathVariable("orderNum") String orderNum) {
		return AjaxResult.success(iTiktokOrderService.queryByOrderNum(orderNum));
	}


	@RepeatSubmit(intervalTime = 1000)
	@ApiOperation("代理商Pc创建订单 order:order:createOrder")
	@PreAuthorize("@ss.hasPermi('order:order:createOrder')")
	@GetMapping("createOrder")
    public AjaxResult createOrder(Long proxyId, Long videoCount, HttpServletResponse response) throws WxPayException {
		if(!SecurityUtils.isProxy()){
			return AjaxResult.error("管理员无需下单");
		}TiktokOrder orderVo = payService.pcCreateOrder(proxyId,videoCount);
		WxPayUnifiedOrderV3Request wxPayUnifiedOrderV3Request = new WxPayUnifiedOrderV3Request();
		wxPayUnifiedOrderV3Request.setOutTradeNo(orderVo.getOrderNum());
		wxPayUnifiedOrderV3Request.setNotifyUrl(qingYunConfig.getProjectUrl() + "/order/notice/payOrder");
		wxPayUnifiedOrderV3Request.setDescription("支付即可获得"+videoCount+"次，"+"约"+videoCount*500+"曝光量");
		WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount();
		BigDecimal mul = NumberUtil.mul(orderVo.getAmount(), 100);
		amount.setTotal(mul.intValue());
		wxPayUnifiedOrderV3Request.setAmount(amount);
		WxPayUnifiedOrderV3Result wxPayUnifiedOrderV3Result = wxPayService.unifiedOrderV3(TradeTypeEnum.NATIVE,wxPayUnifiedOrderV3Request);
		String codeURL = wxPayUnifiedOrderV3Result.getCodeUrl();
		Map<String, Object> result = new HashMap<>();
		result.put("url",codeURL);
		result.put("orderNum",orderVo.getOrderNum());
		return AjaxResult.success(result);
	}

	@ApiOperation("验证是否支付")
	@GetMapping("/isPay")
	public AjaxResult isPay(String orderNum){
		String result = redisCache.getCacheObject("pay_status_" + orderNum);
		if (StringUtils.isNotBlank(result)&&result.equals("success")) {
			return AjaxResult.success(true);
		}
		return AjaxResult.success(false);
	}

	@PostMapping("/notice/payOrder")
	public Map<String, String> pcPayOrder(@RequestBody String data) throws WxPayException {
		Map<String, String> restMap = new HashMap<>();
		WxPayOrderNotifyV3Result wxPayOrderNotifyV3Result = wxPayService.parseOrderNotifyV3Result(data, null);
		if (wxPayOrderNotifyV3Result.getRawData().getEventType().equals("TRANSACTION.SUCCESS")) {
			WxPayOrderNotifyV3Result.DecryptNotifyResult result = wxPayOrderNotifyV3Result.getResult();
			if (result.getTradeState().equals("SUCCESS")) {
				//订单号
				String outTradeNo = result.getOutTradeNo();
				String transactionId = result.getTransactionId();
				payService.pcEndOrder(outTradeNo,transactionId);
			}
		}
		restMap.put("code","SUCCESS");
		restMap.put("message","接收成功");
		return restMap;
	}
}
